<?php

namespace App\Controller;
use Think\Controller;
use Think\Hook;

// +----------------------------------------------------------------------
// | 文件 AjaxAppController.class.php
// +----------------------------------------------------------------------
// | 说明 处理给APP页面AJAX的基类
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
// | Author: 谢赤心 Legend. <xcx_legender@qq.com>
// +----------------------------------------------------------------------

class AjaxAppController extends Controller {

	protected $uid;

	protected function _initialize() {
		$param = [
			'action' => strtolower('App/' . CONTROLLER_NAME . '/' . ACTION_NAME),
		];
		Hook::listen('api_init', $param);
	}

	public function checkUser($appToken) {
		if (!$appToken) {
			return $this->errLogin();
		}

		$uid = $this->getUid($appToken);
		if ($uid <= 0) {
			return $this->errLogin();
		}
		$this->uid = $uid;
	}

	protected function response($status, $data, $info = '') {
		header('Access-Control-Allow-Origin: *');
		header('Access-Control-Allow-Headers: X-Requested-With');
		$res = [
			'status' => $status,
			'data' => $data,
			'info' => $info,
		];
		$format = I('format') == 'jsonp' ? 'jsonp' : 'json';
		$this->ajaxReturn($res, $format);
	}

	protected function showErr($info) {
		$this->response(0, '', $info);
	}

	protected function errLogin() {
		$this->showErrWithStatus(-200, '用户未登录');
	}

	protected function showErrWithStatus($status, $info) {
		$this->response($status, '', $info);
	}

	protected function getUid($appToken = '') {
		// 修改可为空情况
		static $uid = null;
		if ($uid === null) {
			$map = array(
				// 'status' => 1,
				'app_token' => trim($appToken),
			);
			$uid = service('Token')->where($map)->find()['uid'] ?: 0;
 
		}
		return $uid ?: 0;
	}

	protected function jsonList($object) {
		$ret = [];
		$ret['count'] = count($object);
		$ret['lists'] = $object;
		$this->response(1, $ret);
	}

}